package com.clkj.zhonghui.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.clkj.zhonghui.pojo.common.Result;
import com.clkj.zhonghui.pojo.common.StatusCode;
import com.clkj.zhonghui.pojo.common.Util;
import com.clkj.zhonghui.pojo.common.Util1;
import com.clkj.zhonghui.pojo.product.ProductFormat;
import com.clkj.zhonghui.pojo.stored.Version;
import com.clkj.zhonghui.pojo.user.User;
import com.clkj.zhonghui.pojo.user.UserAddr;
import com.clkj.zhonghui.service.user.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import sun.net.www.protocol.http.Handler;
import sun.net.www.protocol.http.HttpURLConnection;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.util.Base64;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author yawang
 * @create 2024/07/19 09:35:29
 **/

@RestController
@RequestMapping(value = "/user")
@Api(value = "/user", tags = {"用户管理"})
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/listUserAddress")
    @ApiOperation(value = "app-获取用户收货地址")
    public Result listUserAddress(Integer userId){
        try {
            List<UserAddr> listAddr = userService.listUserAddress(userId);
            return  new Result(true, StatusCode.OK,"获取成功",listAddr);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false, StatusCode.ERROR,"获取失败");
        }
    }

    @PostMapping("/addUserAddr")
    @ApiOperation(value = "app-添加用户收货地址")
    public Result addUserAddr(UserAddr addUserAddr,Integer flag){
        try {
            userService.addUserAddress(addUserAddr,flag);
            return  new Result(true, StatusCode.OK,"添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false, StatusCode.ERROR,"添加失败");
        }
    }
    @PostMapping("/delUserAddr")
    @ApiOperation(value = "app-删除用户收货地址")
    public Result delUserAddr(Integer addressId){
        try {
            userService.deleteUserAddress(addressId);
            return  new Result(true, StatusCode.OK,"删除成功");
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(false, StatusCode.ERROR,"删除失败");
        }
    }
    @PostMapping("/login")
    @ApiOperation(value = "app-用户登录")
    public Result login(@ApiParam(name = "unionId", value = "unionId") @RequestParam("unionId") String unionId,
                        @ApiParam(name = "openId", value = "openId") @RequestParam("openId") String openId,
                        @ApiParam(name = "userName", value = "用户信息") @RequestParam("userName") String userName,
                        @ApiParam(name = "userImg", value = "头像") @RequestParam("userImg") String userImg,
                        @ApiParam(name = "userSex", value = "性别") @RequestParam("userSex") String userSex){
        try {
            Map map = userService.login(unionId,openId,userName,userImg,userSex);
            return  new Result(true, StatusCode.OK,"成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return  new Result(true, StatusCode.ERROR,"失败");
        }
    }

    @PostMapping("/editUser")
    @ApiOperation(value = "更新用户信息")
    public Result editUser(User user, HttpServletRequest request){
        try {
            User u = userService.EditUser(user,request);
            return new Result(true, StatusCode.OK, "更新成功",u);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "更新失败");
        }
    }

    @PostMapping("/editUsernameAndTf")
    @ApiOperation(value = "更新用户信息(姓名电话)")
    public Result editUsernameAndTf(@ApiParam(name = "userTel", value = "电话") @RequestParam("userTel") String userTel,
                           @ApiParam(name = "name", value = "用户名") @RequestParam("name") String name,
                           @ApiParam(name = "userId", value = " 用户ID") @RequestParam("userId") Integer userId){
        try {
            userService.editUsernameAndTf(userTel,name,userId);
            return new Result(true, StatusCode.OK, "更新成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "更新失败");
        }
    }

    @ApiOperation(value = "获取最新版本")
    @PostMapping("/listNewVer")
    public Result listNewVer() {
        try {
            List<Version> vers = userService.listNewVer();
            return new Result(true, StatusCode.OK, "操作成功", vers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "操作失败");
        }
    }

    @ApiOperation(value = "获取App版本更新记录")
    @PostMapping("/listVer")
    public Result listVer() {
        try {
            List<Version> vers = userService.listVer();
            return new Result(true, StatusCode.OK, "操作成功", vers);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "操作失败");
        }
    }
    @ApiOperation(value = "测试添加版本")
    @PostMapping("/addVer")
    public Result addVer(Version version){
        try {
            userService.addVer(version);
            return new Result(true, StatusCode.OK, "获取成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "获取失败");
        }
    }

    @PostMapping("/loginMini")
    @ApiOperation(value = "小程序登录")
    public Result loginMini(@ApiParam(name = "code", value = "小程序传来的code") @RequestParam("code") String code,
                            @ApiParam(name = "parentId", value = "父级ID,没有传0") @RequestParam("parentId") Integer parentId) {
        try {
            Map map = userService.loginMini(code,parentId);
            return new Result(true, StatusCode.OK, "成功", map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, StatusCode.ERROR, "失败");
        }
    }

    @PostMapping("/selectUser")
    @ApiOperation(value = "获取用户信息")
    public Result selectUser(@ApiParam(name = "flag", value = " 0 根据id搜索1 根据用户名搜索") @RequestParam("flag") Integer flag,
                             @ApiParam(name = "name", value = "用户名") @RequestParam("name") String name,
                             @ApiParam(name = "id", value = " 用户ID") @RequestParam("id") Integer id){
        try {
            List<User> u = userService.selectUser(flag,name,id);
            return new Result(true, StatusCode.OK, "查询成功",u);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "查询失败");
        }
    }

    @PostMapping("/listLowerUser")
    @ApiOperation(value = "获取用户下级（下两级）")
    public Result listLowerUser(@ApiParam(name="userId",value = "用户ID")@RequestParam Integer userId){
        try {
            Map map =  userService.listLowerUser(userId);
            return new Result(true, StatusCode.OK,"查询成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"查询失败");
        }
    }
    @PostMapping("/listHigherUser")
    @ApiOperation(value = "获取用户上级(上两级)")
    public Result listHigherUser(@ApiParam(name="userId",value = "用户ID")@RequestParam Integer userId){
        try {
            Map map =  userService.listHigherUser(userId);
            return new Result(true, StatusCode.OK,"查询成功",map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"查询失败");
        }
    }


    @PostMapping("cenerateTheQrCode")
    @ApiOperation(value = "生成小程序二维码")
    public Object cenerateTheQrCode(@ApiParam(name = "userId", value = "用户ID") @RequestParam("userId") Integer userId,
                                    HttpServletRequest request) {
        // 微信接口地址，用于获取access_token 用户邀请二维码
        String urls = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wxc654e2d4c9a8cf7f&secret=4826eb440a04bb382103945ae6ea8421";
        JSONObject demoJson = Util1.getResult(urls);
        // 从JSON对象中获取access_token
        String accessToken = demoJson.get("access_token").toString();
        Map<String, Object> params = new HashMap<>();
        //参数,一个可以直接放入参数例如:1 多个例如：id=1&name=2&...
        params.put("scene", userId);
        params.put("page", "pages/index/index"); //扫码后进入小程序的页面位置
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
        httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
        String body = JSON.toJSONString(params);
        StringEntity entity = null;
        try {
            // 将body转换为StringEntity对象，并设置内容类型为image/png
            entity = new StringEntity(body);
            entity.setContentType("image/png");
            // 将entity设置到httpPost的请求体中
            httpPost.setEntity(entity);
            // 执行请求，获取响应
            HttpResponse response;
            response = httpClient.execute(httpPost);
            // 从响应中获取输入流
            InputStream inputStream = response.getEntity().getContent();
            // 设置图片文件名，由userId和后缀组成
            String picName = userId + ".png";
            // 设置图片保存路径
            //String path = "D:\\test";
            String path = "D:\\nginx-1.19.1\\html\\zhonghui\\resource\\usermini\\";
            // 调用Util1.saveToImgByInputStream方法，将输入流保存为图片
            Util1.saveToImgByInputStream(inputStream, path, picName);
        } catch (Exception e) {
            // 打印异常堆栈信息
            e.printStackTrace();
        }
        // 返回success，表示生成二维码成功
        return "success";
    }

    @PostMapping("/unbindUser")
    @ApiOperation(value = "用户解绑")
    public Result unbindUser(@ApiParam(name="userId",value = "用户ID（和上级解绑传自己的userid,和下级解绑传下级的用户ID）")@RequestParam Integer userId){
        try {
            userService.unbindUser(userId);
            return new Result(true, StatusCode.OK,"解绑成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR,"解绑失败");
        }
    }

}
